#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>

#include "Common.hpp"
#include "Log.hpp"

using namespace My_Log;

int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        exit(USAGE_ERR);
    }

    in_port_t serport = std::stoi(argv[2]);
    std::string serip = argv[1];
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket err: " << strerror(errno);
        exit(SOCKET_ERR);
    }

    struct sockaddr_in seraddr;
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = ntohs(serport);
    seraddr.sin_addr.s_addr = inet_addr(serip.c_str());

    while (true)
    {
        std::string sendstr;
        std::cin >> sendstr;
        sendto(sockfd, sendstr.c_str(), sendstr.size(), 0, CONV(&seraddr), sizeof(seraddr));


        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, CONV(&temp), &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}